from WebBackend.dataclass.Configuration import ConfigurationItem
from WebBackend.store.functions.configuration_functions import read_configuration_file, configuration_liner_comparator
from WebBackend.utils import mylog


class ConfigurationStore:
    def __init__(self, true_config_file: str = ''):
        self.config_file_path = true_config_file
        self.data: dict = {}  # {'listen': 'NO', 'listen_ipv6': 'YES', .......}
        self.reload_store()
        #################################
        self.SEA_ARCHIVER_DELETE_FLAG = '%SEA-ARCHIVER-DELETE-FLAG%'

    def get_data_by_key(self, key: str | list[str], lower: bool = False) -> str | dict | None | list:
        """从<dict> self.data中根据键名获取值"""
        if type(key) is str:
            v = self.data.get(key)
            if type(v) is str:
                if lower:
                    v = v.lower()
            if type(v) is None:
                v = ''
            return v
        elif type(key) is list:
            resultSet = []
            for item in key:
                v = self.data.get(item)
                if type(v) is str:
                    if lower:
                        v = v.lower()
                resultSet.append(v)
            return resultSet
        else:
            raise TypeError("df")

    def configuration_item_wrapper(self, option_item: ConfigurationItem) -> dict:
        value = self.get_data_by_key(option_item['key'])
        if value=='' or value is None:
            if option_item['key'] in self.data.keys():
                value = "%空值%"
                bool_activated = True
            else:
                value = "已禁用"
                bool_activated = False
        else:
            bool_activated = True

        return {
            "key": option_item['key'],
            "value": value,
            "default": option_item['default'],
            "description": option_item['description'],
            "active": bool_activated,
        }

    ####################
    def update_data_by_key(self, key, value='', action='edit', write=True):
        if action == 'edit':
            self.data[key] = value
            print(value, self.data[key])
            if write:
                self.dump_configuration_store()
        elif action == 'delete':
            self.data.pop(key, None)
            if write:
                self.dump_configuration_store()
        else:
            mylog.error('unkown action')

    ##########################################################
    def reload_store(self, return_type='None') -> None:
        """read configuration file and update self.data"""
        self.data = read_configuration_file(file_path=self.config_file_path, return_type='config_dict')

    def dump_configuration_store(self):
        """write whole store into configuration file"""
        ###### 准备数据 #####
        old_lines: list[str] = read_configuration_file(file_path=self.config_file_path, return_type='text_lines')
        new_lines: list[str] = [
            f"{key}={value.upper() if value in ('yes', 'no') else value}"
            for key, value in self.data.items()
        ]

        ##### 比较数据处理日志 #####
        created, removed = configuration_liner_comparator(old_lines, new_lines, ['created', 'removed'])
        mylog.data(f'Configuration updated: [DumpStore]$created:{created} $deleted:{removed}')
        ##### 比较数据，获取日志 #####
        with open(self.config_file_path, 'w') as f:
            f.writelines([line + '\n' for line in new_lines])
            f.close()
        return True
